package com.example.composableexample

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn


/**
 * author: LiLiang
 * createTime: 2022/9/26-21:03
 * remark:
 **/

@Preview
@Composable
fun CalculatorPreview() {
    val viewModel = viewModel<CalculatorViewModel>()
    Calculator(state = viewModel)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Calculator(state: CalculatorViewModel) {
    Column {
        TextField(
            value = state.v1,
            onValueChange = { state.v1 = it }
        )
        TextField(
            value = state.v2,
            onValueChange = { state.v2 = it }
        )
        Text(text = state.result)
    }
}

@OptIn(ExperimentalCoroutinesApi::class)
class CalculatorViewModel : ViewModel() {
    var v1 by mutableStateOf("")
    var v2 by mutableStateOf("")
    var result by mutableStateOf("")
        private set

    init {
        snapshotFlow { v1 to v2 }.mapLatest {
            sum(it.first, it.second)
        }.onEach { result = it }.launchIn(viewModelScope)
    }

}

class CalculatorState {
    var v1 by mutableStateOf("0")
    var v2 by mutableStateOf("0")

    @OptIn(ExperimentalCoroutinesApi::class)
    val result
        get() = snapshotFlow { v1 to v2 }.mapLatest {
            sum(it.first, it.second)
        }
}

suspend fun sum(v1: String, v2: String) = try {
    (v1.toInt() + v2.toInt()).toString()
} catch (e: NumberFormatException) {
    e.printStackTrace()
    "Parsing error"
}